import Result from '../utils/result.js';
import HealthData from '../models/healthData.js';
import { Op } from 'sequelize';
import moment from 'moment';

// 计算日期范围
function getDateRange(period) {
    // 使用本地时间
    const endDate = moment().local().endOf('day');
    let startDate;
    
    if (period === 'day') {
        startDate = moment().local().startOf('day');
    } else if (period === 'week') {
        // 修改为计算当前自然周的开始和结束日期 (周一到周日)
        startDate = moment().local().startOf('isoWeek'); // 本周一
        // 确保结束日期不超过今天
        if (endDate.isAfter(moment().local().endOf('day'))) {
            endDate = moment().local().endOf('day');
        }
    } else if (period === 'month') {
        startDate = moment().local().startOf('month');
    }

    return { 
        startDate: startDate.toDate(),
        endDate: endDate.toDate() 
    };
}

    // 辅助函数：获取血氧状态文本
    const getSpo2StatusText = (value) => {
        if (value < 90) return '危险';
        if (value < 95) return '偏低';
        return '正常';
    }
    
    // 辅助函数：获取血氧状态类名
    const getSpo2StatusClass = (value) => {
        if (value < 90) return 'danger';
        if (value < 95) return 'warning';
        return 'normal';
    }

const healthDataService = {
    async getRealData(userId) {


        try {
            // Fetch the latest 20 health data records for the user, ordered by collectTime descending
            const recentHealthData = await HealthData.findAll({
                where: {
                    userId: userId,
                },
                order: [['collectTime', 'DESC']],
                limit: 50, // Adjust limit as needed to capture data from all relevant devices
            });

             

            // Reverse the array to process from oldest to newest
            recentHealthData.reverse();

            // Combine data from recent records, prioritizing newer data
            let combinedData = {
                id: userId,
                healthStatus: 'normal', // Default or derive from combined data
                heartRate: null,
                bloodOxygen: null,
                bloodPressureHigh: null,
                bloodPressureLow: null,
                bodyTemperature: null,
                otherData: {}, // Initialize otherData as an empty object
                collectTime: null, // Will be the collectTime of the most recent record used
            };

            // Iterate from oldest to newest record
            for (const data of recentHealthData) {
                // Update fields. Newer data will overwrite older data.
                 combinedData.healthStatus = data.healthStatus || combinedData.healthStatus; // Keep the non-normal status if present
                 combinedData.heartRate = data.heartRate !== null ? data.heartRate : combinedData.heartRate;
                 combinedData.bloodOxygen = data.bloodOxygen !== null ? data.bloodOxygen : combinedData.bloodOxygen;
                 combinedData.bloodPressureHigh = data.bloodPressureHigh !== null ? data.bloodPressureHigh : combinedData.bloodPressureHigh;
                 combinedData.bloodPressureLow = data.bloodPressureLow !== null ? data.bloodPressureLow : combinedData.bloodPressureLow;
                 combinedData.bodyTemperature = data.bodyTemperature !== null ? data.bodyTemperature : combinedData.bodyTemperature;
                
                // Merge otherData fields - newer properties will overwrite older ones
                if (data.otherData) {
                    combinedData.otherData = { ...combinedData.otherData, ...data.otherData };
                }

                // Set the collectTime to the time of the most recent record processed
                 combinedData.collectTime = data.collectTime || combinedData.collectTime;
            }

            // Optionally, if no non-normal status was found, check for slight status
            // This logic needs adjustment if iterating oldest to newest
            // Let's re-evaluate healthStatus based on combined data at the end
             if (combinedData.healthStatus === 'normal') {
                 if (combinedData.bloodOxygen !== null && combinedData.bloodOxygen < 95) combinedData.healthStatus = 'slight';
                 if (combinedData.bodyTemperature !== null && combinedData.bodyTemperature > 37.3) combinedData.healthStatus = 'slight';
                 if (combinedData.bloodPressureHigh !== null && combinedData.bloodPressureHigh >= 120) combinedData.healthStatus = 'slight';
                 if (combinedData.bloodPressureLow !== null && combinedData.bloodPressureLow >= 80) combinedData.healthStatus = 'slight';
                 // Add other conditions for slight status based on other metrics if needed
             }
             // Prioritize more severe statuses if present in the raw data (requires re-checking raw data)
             // A simpler approach for healthStatus with oldest-to-newest merge:
             // Start with 'normal', and update to 'slight', 'medium', 'severe' as encountered in newer data
             let finalHealthStatus = 'normal';
             for(const data of recentHealthData.slice().reverse()) { // Iterate newest to oldest again for status priority
                  if(data.healthStatus && data.healthStatus !== 'normal') {
                       finalHealthStatus = data.healthStatus;
                       break;
                  }
             }
             combinedData.healthStatus = finalHealthStatus;


            return Result.success(combinedData, '获取实时健康数据成功');
        } catch (e) {
            console.error('Error in getRealData:', e);
            return Result.error(e.message);
        }
    },

    async getHistory(userId, startDate, endDate) {
        try {
            console.log('原始时间范围:', {
                startDate: moment(startDate).format('YYYY-MM-DD HH:mm:ss'),
                endDate: moment(endDate).format('YYYY-MM-DD HH:mm:ss')
            });

            // 转换为本地时间
            const localStartDate = moment(startDate).local().toDate();
            const localEndDate = moment(endDate).local().toDate();

            console.log('转换后的本地时间范围:', {
                startDate: moment(localStartDate).format('YYYY-MM-DD HH:mm:ss'),
                endDate: moment(localEndDate).format('YYYY-MM-DD HH:mm:ss')
            });

            let healthData = await HealthData.findAll({
                where: {
                    userId: userId,
                    collectTime: {
                        [Op.between]: [localStartDate, localEndDate],
                    },
                },
            });

            // 打印查询到的数据的时间范围
            if (healthData.length > 0) {
                console.log('查询到的数据时间范围:', {
                    first: moment(healthData[0].collectTime).format('YYYY-MM-DD HH:mm:ss'),
                    last: moment(healthData[healthData.length - 1].collectTime).format('YYYY-MM-DD HH:mm:ss')
                });
            }

            return Result.success(healthData, '获取历史健康数据成功');
        } catch (e) {
            console.error('Error in getHistory:', e);
            return Result.error(e.message);
        }
    },

    async statisticHeartRate(data, period, startDate) {
        try {
            if (!data || data.length === 0) {
                return Result.error('No data available');
            }

            // 过滤掉无效的心率数据
            const validData = data.filter(item => 
                item && 
                typeof item.heartRate === 'number' && 
                !isNaN(item.heartRate) && 
                item.heartRate > 0 && 
                item.collectTime
            );

            if (validData.length === 0) {
                return Result.error('No valid heart rate data available');
            }

            // 按时间排序
            const sortedData = validData.sort((a, b) => new Date(a.collectTime) - new Date(b.collectTime));
            
            // 计算基础统计数据
            const heartRates = sortedData.map(item => item.heartRate);
            const avg = Math.round(heartRates.reduce((a, b) => a + b, 0) / heartRates.length);
            
            // 找出最大值和最小值及其时间
            const max = Math.max(...heartRates);
            const min = Math.min(...heartRates);
            const maxItem = sortedData.find(item => item.heartRate === max);
            const minItem = sortedData.find(item => item.heartRate === min);
            
            const maxTime = maxItem ? maxItem.collectTime : new Date();
            const minTime = minItem ? minItem.collectTime : new Date();

            // 计算心率区间分布
            const zones = {
                rest: heartRates.filter(hr => hr < 60).length,
                fatBurn: heartRates.filter(hr => hr >= 60 && hr < 70).length,
                aerobic: heartRates.filter(hr => hr >= 70 && hr < 80).length,
                extreme: heartRates.filter(hr => hr >= 80).length
            };

            const total = heartRates.length;
            const zonePercentages = {
                rest: Math.round((zones.rest / total) * 100),
                fatBurn: Math.round((zones.fatBurn / total) * 100),
                aerobic: Math.round((zones.aerobic / total) * 100),
                extreme: Math.round((zones.extreme / total) * 100)
            };

            if (period === 'day') {
                // 定义时间间隔（每3小时）
                const timeIntervals = [
                    { label: '0', startHour: 0, endHour: 3 },
                    { label: '3', startHour: 3, endHour: 6 },
                    { label: '6', startHour: 6, endHour: 9 },
                    { label: '9', startHour: 9, endHour: 12 },
                    { label: '12', startHour: 12, endHour: 15 },
                    { label: '15', startHour: 15, endHour: 18 },
                    { label: '18', startHour: 18, endHour: 21 },
                    { label: '21', startHour: 21, endHour: 24 }
                ];

                // 按时间间隔分组数据并计算平均值
                const groupedData = timeIntervals.map(interval => ({
                    label: interval.label,
                    data: []
                }));

                sortedData.forEach(item => {
                    const itemHour = moment(item.collectTime).hour();
                    const itemMinute = moment(item.collectTime).minute();
                    const interval = timeIntervals.find(interval =>
                        itemHour > interval.startHour || (itemHour === interval.startHour && itemMinute >= 0) &&
                        itemHour < interval.endHour || (itemHour === interval.endHour && itemMinute === 0 && interval.endHour === 24) // Handle 24:00 case
                    );
                    // Fix: Correct interval finding logic
                    const correctInterval = timeIntervals.find(interval => {
                        const start = moment().startOf('day').add(interval.startHour, 'hours');
                        const end = moment().startOf('day').add(interval.endHour, 'hours');
                        const itemTime = moment(item.collectTime);
                        return itemTime.isBetween(start, end, null, '[)'); // [) means inclusive of start, exclusive of end
                    });

                    if (correctInterval) {
                        const groupIndex = timeIntervals.indexOf(correctInterval);
                        groupedData[groupIndex].data.push(item.heartRate);
                    }
                });

                // 计算每个时间间隔的平均心率值
                const timeSeriesDataWithZero = groupedData.map(group => ({
                    time: group.label,
                    value: group.data.length > 0 ? Math.round(group.data.reduce((sum, val) => sum + val, 0) / group.data.length) : 0 // 使用0填充没有数据的间隔
                }));

                return {
                    avg,
                    max,
                    maxTime: moment(maxTime).format('HH:mm'),
                    min,
                    minTime: moment(minTime).format('HH:mm'),
                    zones: [
                        { name: "休息区", range: "<60", percentage: zonePercentages.rest, color: "#93C5FD" },
                        { name: "燃脂区", range: "60-70", percentage: zonePercentages.fatBurn, color: "#60A5FA" },
                        { name: "有氧区", range: "70-80", percentage: zonePercentages.aerobic, color: "#3B82F6" },
                        { name: "极限区", range: "80+", percentage: zonePercentages.extreme, color: "#EE6666" }
                    ],
                    chartData: {
                        categories: timeIntervals.map(interval => interval.label),
                        series: [
                            {
                                name: "平均心率",
                                data: timeSeriesDataWithZero.map(item => item.value)
                            }
                        ]
                    }
                };
            } else if (period === 'week') {
                // 按天分组数据
                const weekDays = ['周一', '周二', '周三', '周四', '周五', '周六', '周日'];

                // 使用传入的时间范围来确定周的开始和结束日期 (周一到周日)
                const startOfWeek = moment(startDate).startOf('isoWeek');
                const daysData = weekDays.map((dayName, index) => {
                    const date = startOfWeek.clone().add(index, 'days');
                    const isFutureDate = date.isAfter(moment().endOf('day'));
                    return {
                        name: dayName,
                        date: date.format('YYYY-MM-DD'),
                        avg: 0,
                        min: 0,
                        max: 0,
                        spo2Values: [],
                        isFutureDate
                    };
                });

                sortedData.forEach(item => {
                    const itemDate = moment(item.collectTime).format('YYYY-MM-DD');
                    const day = daysData.find(d => d.date === itemDate);

                    if (day && !day.isFutureDate) {
                       day.spo2Values.push(item.heartRate);
                    }
                });

                // 计算每日统计数据并填充未来日期
                const days = daysData.map(day => {
                    if (day.isFutureDate) {
                        return {
                            name: day.name,
                            avg: 0,
                            min: 0,
                            max: 0
                        };
                    }

                    const daySpo2Values = day.spo2Values;
                    const dayAvg = daySpo2Values.length ? Math.round(daySpo2Values.reduce((a, b) => a + b, 0) / daySpo2Values.length) : 0;
                    const dayMin = daySpo2Values.length ? Math.min(...daySpo2Values) : 0;
                    const dayMax = daySpo2Values.length ? Math.max(...daySpo2Values) : 0;

                    return {
                        name: day.name,
                        avg: dayAvg,
                        min: dayMin,
                        max: dayMax
                    };
                });

                // 周图表数据 (使用每日平均值)
                const chartData = {
                    categories: weekDays,
                    series: [
                        {
                            name: "平均心率",
                            data: days.map(day => day.avg)
                        }
                    ]
                };

                return {
                    avg, // 周平均心率保持不变
                    days,
                    chartData
                };
            }

            return Result.error('Invalid period');
        } catch (e) {
            console.error('Error in statisticHeartRate:', e);
            return Result.error(e.message);
        }
    },

    async statisticBloodPressure(data, period, startDate) {
        try {
            if (!data || data.length === 0) {
                return Result.error('No data available');
            }

            // 过滤掉无效的血压数据
            const validData = data.filter(item => 
                item && 
                typeof item.bloodPressureHigh === 'number' && 
                !isNaN(item.bloodPressureHigh) && 
                item.bloodPressureHigh > 0 &&
                typeof item.bloodPressureLow === 'number' && 
                !isNaN(item.bloodPressureLow) && 
                item.bloodPressureLow > 0 &&
                item.collectTime
            );

            if (validData.length === 0) {
                return Result.error('No valid blood pressure data available');
            }

            // 按时间排序
            const sortedData = validData.sort((a, b) => new Date(a.collectTime) - new Date(b.collectTime));
            
            // 计算基础统计数据
            const systolicPressures = sortedData.map(item => item.bloodPressureHigh);
            const diastolicPressures = sortedData.map(item => item.bloodPressureLow);
            
            // 计算平均值
            const avgSystolic = Math.round(systolicPressures.reduce((a, b) => a + b, 0) / systolicPressures.length);
            const avgDiastolic = Math.round(diastolicPressures.reduce((a, b) => a + b, 0) / diastolicPressures.length);
            
            // 找出最大值和最小值及其时间
            const maxSystolic = Math.max(...systolicPressures);
            const minSystolic = Math.min(...systolicPressures);
            const maxDiastolic = Math.max(...diastolicPressures);
            const minDiastolic = Math.min(...diastolicPressures);
            
            const maxItem = sortedData.find(item => 
                item.bloodPressureHigh === maxSystolic && 
                item.bloodPressureLow === maxDiastolic
            );
            
            const minItem = sortedData.find(item => 
                item.bloodPressureHigh === minSystolic && 
                item.bloodPressureLow === minDiastolic
            );
            
            const maxTime = maxItem ? maxItem.collectTime : new Date();
            const minTime = minItem ? minItem.collectTime : new Date();

            // 计算血压分级
            const getBpLevel = (systolic, diastolic) => {
                if (systolic >= 140 || diastolic >= 90) return { level: 'very-high', position: 87.5 };
                if (systolic >= 120 || diastolic >= 80) return { level: 'high', position: 62.5 };
                if (systolic <= 90 || diastolic <= 60) return { level: 'low', position: 12.5 };
                return { level: 'normal', position: 37.5 };
            };

            // 生成医生建议
            const generateAdvice = (systolic, diastolic) => {
                if (systolic >= 140 || diastolic >= 90) {
                    return "血压偏高，建议及时就医，控制饮食，避免剧烈运动。";
                } else if (systolic >= 120 || diastolic >= 80) {
                    return "血压略高，建议减少钠盐摄入，保持适度运动，避免情绪激动。";
                } else if (systolic <= 90 || diastolic <= 60) {
                    return "血压偏低，建议适当增加盐分摄入，保持充足休息。";
                }
                return "血压正常，请继续保持健康的生活方式。";
            };

            if (period === 'day') {
                // 按时间段分组数据（6:00, 9:00, 12:00, 15:00, 18:00, 21:00, 24:00）
                const timeSlots = ['06:00', '09:00', '12:00', '15:00', '18:00', '21:00', '24:00'];
                const timeSlotData = {};
                
                sortedData.forEach(item => {
                    const time = moment(item.collectTime).format('HH:mm');
                    const slot = timeSlots.find(slot => moment(time, 'HH:mm').isSameOrBefore(moment(slot, 'HH:mm')));
                    if (slot) {
                        if (!timeSlotData[slot]) {
                            timeSlotData[slot] = [];
                        }
                        timeSlotData[slot].push({
                            systolic: item.bloodPressureHigh,
                            diastolic: item.bloodPressureLow
                        });
                    }
                });

                // 计算每个时间段的平均值
                const systolicData = timeSlots.map(slot => {
                    const slotData = timeSlotData[slot] || [];
                    if (!slotData.length) return 0;
                    const avg = Math.round(slotData.reduce((sum, item) => sum + item.systolic, 0) / slotData.length);
                    return avg;
                });

                const diastolicData = timeSlots.map(slot => {
                    const slotData = timeSlotData[slot] || [];
                    if (!slotData.length) return 0;
                    const avg = Math.round(slotData.reduce((sum, item) => sum + item.diastolic, 0) / slotData.length);
                    return avg;
                });

                const level = getBpLevel(avgSystolic, avgDiastolic);
                return {
                    avgValue: `${avgSystolic}/${avgDiastolic} mmHg`,
                    highValue: `${maxSystolic}/${maxDiastolic} mmHg`,
                    highTime: moment(maxTime).format('HH:mm'),
                    lowValue: `${minSystolic}/${minDiastolic} mmHg`,
                    lowTime: moment(minTime).format('HH:mm'),
                    levelPosition: level.position,
                    advice: generateAdvice(avgSystolic, avgDiastolic),
                    chartData: {
                        categories: timeSlots,
                        series: [{
                            name: "收缩压",
                            data: systolicData
                        },{
                            name: "舒张压",
                            data: diastolicData
                        }]
                    }
                };
            } else if (period === 'week') {
                // 按天分组数据
                const weekDays = ['周一', '周二', '周三', '周四', '周五', '周六', '周日'];

                // 初始化本周所有日期的数据，未来日期填充0
                const startOfWeek = moment(startDate).startOf('isoWeek');
                const daysData = weekDays.map((dayName, index) => {
                    const date = startOfWeek.clone().add(index, 'days');
                    const isFutureDate = date.isAfter(moment().endOf('day'));
                    return {
                        name: dayName,
                        date: date.format('YYYY-MM-DD'),
                        systolic: 0, // 收缩压
                        diastolic: 0, // 舒张压
                        dataPoints: [] // 存储原始血压数据点用于计算
                    };
                });

                sortedData.forEach(item => {
                    const itemDate = moment(item.collectTime).format('YYYY-MM-DD');
                    const day = daysData.find(d => d.date === itemDate);

                    if (day) {
                       day.dataPoints.push({ systolic: item.bloodPressureHigh, diastolic: item.bloodPressureLow });
                    }
                });

                // 计算每日统计数据并填充未来日期
                const days = daysData.map(day => {
                    const dayDataPoints = day.dataPoints;
                    let latestSystolic = 0;
                    let latestDiastolic = 0;

                    if(dayDataPoints.length > 0) {
                        // 使用当天最新的一个数据点作为代表
                         const latestDataPoint = dayDataPoints[dayDataPoints.length - 1];
                         latestSystolic = latestDataPoint.systolic;
                         latestDiastolic = latestDataPoint.diastolic;
                    }

                    return {
                        name: day.name,
                        value: `${latestSystolic}/${latestDiastolic}`, // 显示最新的血压值
                        time: dayDataPoints.length > 0 ? moment(sortedData.find(item => moment(item.collectTime).format('YYYY-MM-DD') === day.date).collectTime).format('HH:mm') : "--:--", // 显示最新数据的时间
                        systolic: latestSystolic,
                        diastolic: latestDiastolic
                    };
                });

                return {
                    avgValue: `${avgSystolic}/${avgDiastolic} mmHg`, // 周平均值保持不变
                    days,
                    chartData: {
                        categories: weekDays,
                        series: [
                            {
                                name: "收缩压",
                                data: days.map(day => day.systolic)
                            },
                            {
                                name: "舒张压",
                                data: days.map(day => day.diastolic)
                            }
                        ]
                    }
                };
            }

            return Result.error('Invalid period');
        } catch (e) {
            console.error('Error in statisticBloodPressure:', e);
            return Result.error(e.message);
        }
    },

    async statisticBodyTemperature(data, period, startDate) {
        try {
            if (!data || data.length === 0) {
                return Result.error('No data available');
            }

            // 过滤掉无效的体温数据
            const validData = data.filter(item => 
                item && 
                typeof item.bodyTemperature === 'number' && 
                !isNaN(item.bodyTemperature) && 
                item.bodyTemperature > 35 && // 正常体温范围
                item.bodyTemperature < 42 && // 正常体温范围
                item.collectTime
            );

            if (validData.length === 0) {
                return Result.error('No valid body temperature data available');
            }

            // 按时间排序
            const sortedData = validData.sort((a, b) => new Date(a.collectTime) - new Date(b.collectTime));
            
            // 计算基础统计数据
            const temperatures = sortedData.map(item => item.bodyTemperature);
            const avg = Number((temperatures.reduce((a, b) => a + b, 0) / temperatures.length).toFixed(1));
            
            // 找出最大值和最小值及其时间
            const max = Math.max(...temperatures);
            const min = Math.min(...temperatures);
            const maxItem = sortedData.find(item => item.bodyTemperature === max);
            const minItem = sortedData.find(item => item.bodyTemperature === min);
            
            const maxTime = maxItem ? maxItem.collectTime : new Date();
            const minTime = minItem ? minItem.collectTime : new Date();

            if (period === 'day') {
                return {
                    avg,
                    max,
                    maxTime: moment(maxTime).format('HH:mm'),
                    min,
                    minTime: moment(minTime).format('HH:mm'),
                    status: {
                        text: avg > 37.3 ? '发热' : (avg < 36.0 ? '体温偏低' : '正常'),
                        class: avg > 37.3 ? 'danger' : (avg < 36.0 ? 'warning' : 'normal')
                    }
                };
            } else if (period === 'week') {
                // 按天分组数据
                const weekDays = ['周一', '周二', '周三', '周四', '周五', '周六', '周日'];

                // 初始化本周所有日期的数据，未来日期填充0
                const startOfWeek = moment(startDate).startOf('isoWeek');
                const daysData = weekDays.map((dayName, index) => {
                    const date = startOfWeek.clone().add(index, 'days');
                    const isFutureDate = date.isAfter(moment().endOf('day'));
                    return {
                        name: dayName,
                        date: date.format('YYYY-MM-DD'),
                        avg: 0, // 平均体温
                        min: 0, // 最低体温
                        max: 0, // 最高体温
                        temps: [], // 存储原始体温数据用于计算
                        isFutureDate
                    };
                });

                sortedData.forEach(item => {
                    const itemDate = moment(item.collectTime).format('YYYY-MM-DD');
                    const day = daysData.find(d => d.date === itemDate);

                    if (day) {
                       day.temps.push(item.bodyTemperature);
                    }
                });

                // 计算每日统计数据并填充未来日期
                const days = daysData.map(day => {
                    if (day.isFutureDate) {
                        return {
                            name: day.name,
                            avg: 0,
                            min: 0,
                            max: 0
                        };
                    }

                    const dayTemps = day.temps;
                    const dayAvg = dayTemps.length ? Number((dayTemps.reduce((a, b) => a + b, 0) / dayTemps.length).toFixed(1)) : 0;
                    const dayMin = dayTemps.length ? Math.min(...dayTemps) : 0;
                    const dayMax = dayTemps.length ? Math.max(...dayTemps) : 0;

                    return {
                        name: day.name,
                        avg: dayAvg,
                        min: dayMin,
                        max: dayMax,
                        status: { // 根据每日平均体温判断状态
                            text: dayAvg > 37.3 ? '发热' : (dayAvg > 0 && dayAvg < 36.0 ? '体温偏低' : '正常'), // 当avg为0时不显示体温偏低
                            class: dayAvg > 37.3 ? 'danger' : (dayAvg > 0 && dayAvg < 36.0 ? 'warning' : 'normal')
                        }
                    };
                });

                return {
                    avg, // 周平均体温保持不变
                    days,
                    status: { // 根据周平均体温判断状态
                        text: avg > 37.3 ? '发热' : (avg > 0 && avg < 36.0 ? '体温偏低' : '正常'), // 当avg为0时不显示体温偏低
                        class: avg > 37.3 ? 'danger' : (avg > 0 && avg < 36.0 ? 'warning' : 'normal')
                    }
                };
            }

            return Result.error('Invalid period');
        } catch (e) {
            console.error('Error in statisticBodyTemperature:', e);
            return Result.error(e.message);
        }
    },
    
    async statisticBloodOxygen(data, period, startDate) {
        try {
            if (!data || data.length === 0) {
                return Result.error('No data available');
            }

            // 过滤掉无效的血氧数据
            const validData = data.filter(item => 
                item && 
                typeof item.bloodOxygen === 'number' && 
                !isNaN(item.bloodOxygen) && 
                item.bloodOxygen > 0 && 
                item.bloodOxygen <= 100 && // 血氧饱和度应该在0-100之间
                item.collectTime
            );

            if (validData.length === 0) {
                return Result.error('No valid blood oxygen data available');
            }

            // 按时间排序
            const sortedData = validData.sort((a, b) => new Date(a.collectTime) - new Date(b.collectTime));
            
            // 计算基础统计数据
            const bloodOxygenLevels = sortedData.map(item => item.bloodOxygen);
            const avg = Math.round(bloodOxygenLevels.reduce((a, b) => a + b, 0) / bloodOxygenLevels.length);
            
            // 找出最大值和最小值及其时间
            const max = Math.max(...bloodOxygenLevels);
            const min = Math.min(...bloodOxygenLevels);
            const maxItem = sortedData.find(item => item.bloodOxygen === max);
            const minItem = sortedData.find(item => item.bloodOxygen === min);
            
            const maxTime = maxItem ? maxItem.collectTime : new Date();
            const minTime = minItem ? minItem.collectTime : new Date();
    
            // 计算血氧状态分布
            const status = {
                danger: bloodOxygenLevels.filter(bo => bo < 90).length,
                warning: bloodOxygenLevels.filter(bo => bo >= 90 && bo < 95).length,
                normal: bloodOxygenLevels.filter(bo => bo >= 95).length
            };
    
            const total = bloodOxygenLevels.length;
            const statusPercentages = {
                danger: Math.round((status.danger / total) * 100),
                warning: Math.round((status.warning / total) * 100),
                normal: Math.round((status.normal / total) * 100)
            };
    
            if (period === 'day') {
                // 定义时间间隔（每6小时）
                const timeIntervals = [
                    { label: '0-6', startHour: 0, endHour: 6 },
                    { label: '6-12', startHour: 6, endHour: 12 },
                    { label: '12-18', startHour: 12, endHour: 18 },
                    { label: '18-24', startHour: 18, endHour: 24 }
                ];

                // 按时间间隔分组数据并计算平均值
                const groupedData = timeIntervals.map(interval => ({
                    label: interval.label,
                    data: []
                }));

                sortedData.forEach(item => {
                    const itemHour = moment(item.collectTime).hour();
                    const interval = timeIntervals.find(interval =>
                        itemHour >= interval.startHour && (itemHour < interval.endHour || (interval.endHour === 24 && itemHour >= 18)) // Handle 24:00 case for 18-24 interval
                    );
                    if (interval) {
                        const groupIndex = timeIntervals.indexOf(interval);
                        groupedData[groupIndex].data.push(item.bloodOxygen);
                    }
                });

                // 计算每个时间间隔的平均血氧值
                const timeSeriesDataWithZero = groupedData.map(group => ({
                    time: group.label,
                    value: group.data.length > 0 ? Math.round(group.data.reduce((sum, val) => sum + val, 0) / group.data.length) : 0 // 使用0填充没有数据的间隔
                }));

                return {
                    avg,
                    max,
                    maxTime: moment(maxTime).format('HH:mm'),
                    min,
                    minTime: moment(minTime).format('HH:mm'),
                    status: {
                        text: getSpo2StatusText(avg),
                        class: getSpo2StatusClass(avg)
                    },
                    scale: [
                        {label: "危险", width: 1, color: "#EE6666", range: "<90%"},
                        {label: "偏低", width: 2, color: "#FAC858", range: "90-94%"},
                        {label: "正常", width: 3, color: "#91CB74", range: "95-100%"}
                    ],
                    // 返回按时间间隔聚合的数据
                    timeSeriesData: timeSeriesDataWithZero
                };
            } else if (period === 'week') {
                // 按天分组数据
                const weekDays = ['周一', '周二', '周三', '周四', '周五', '周六', '周日'];

                // 使用传入的时间范围来确定周的开始和结束
                const startOfWeek = moment(startDate).startOf('isoWeek');
                const daysData = weekDays.map((dayName, index) => {
                    const date = startOfWeek.clone().add(index, 'days');
                    const isFutureDate = date.isAfter(moment().endOf('day'));
                    return {
                        name: dayName,
                        date: date.format('YYYY-MM-DD'),
                        avg: 0,
                        min: 0,
                        max: 0,
                        spo2Values: [],
                        isFutureDate
                    };
                });

                sortedData.forEach(item => {
                    const itemDate = moment(item.collectTime).format('YYYY-MM-DD');
                    const day = daysData.find(d => d.date === itemDate);

                    if (day && !day.isFutureDate) {
                       day.spo2Values.push(item.bloodOxygen);
                    }
                });

                // 计算每日统计数据并填充未来日期
                const days = daysData.map(day => {
                    if (day.isFutureDate) {
                        return {
                            name: day.name,
                            avg: 0,
                            min: 0,
                            max: 0
                        };
                    }

                    const daySpo2Values = day.spo2Values;
                    const dayAvg = daySpo2Values.length ? Math.round(daySpo2Values.reduce((a, b) => a + b, 0) / daySpo2Values.length) : 0;
                    const dayMin = daySpo2Values.length ? Math.min(...daySpo2Values) : 0;
                    const dayMax = daySpo2Values.length ? Math.max(...daySpo2Values) : 0;

                    return {
                        name: day.name,
                        avg: dayAvg,
                        min: dayMin,
                        max: dayMax
                    };
                });

                // 周图表数据 (使用每日平均值)
                const chartData = {
                    categories: weekDays,
                    series: [
                        {
                            name: "平均血氧",
                            data: days.map(day => day.avg)
                        }
                    ]
                };

                return {
                    avg, // 周平均血氧保持不变
                    days,
                    chartData
                };
            }
    
            return Result.error('Invalid period');
        } catch (e) {
            console.error('Error in statisticBloodOxygen:', e);
            return Result.error(e.message);
        }
    },
    


    async getStatistics(userId, period, type) {
        try {
            const { startDate, endDate } = getDateRange(period);


            const result = await this.getHistory(userId, startDate, endDate);

            if (!result.data || result.data.length === 0) {
                return Result.notfound('No health data found');
            }

            // 根据类型调用对应的统计函数
            switch (type) {
                case 'heartRate':
                    return Result.success(await this.statisticHeartRate(result.data, period, startDate),'统计心率数据成功');
                case 'bloodPressure':
                    return Result.success(await this.statisticBloodPressure(result.data, period, startDate),'统计血压数据成功');
                case 'bloodOxygen':
                    return Result.success(await this.statisticBloodOxygen(result.data, period, startDate),'统计血氧数据成功');
                case 'bodyTemperature':
                    return Result.success(await this.statisticBodyTemperature(result.data, period, startDate),'统计体温数据成功');
                case 'all':
                    const heartRateStats = await this.statisticHeartRate(result.data, period, startDate);
                    const bloodPressureStats = await this.statisticBloodPressure(result.data, period, startDate);
                    const bloodOxygenStats = await this.statisticBloodOxygen(result.data, period, startDate);
                    const bodyTemperatureStats = await this.statisticBodyTemperature(result.data, period, startDate);
                    
                    return Result.success({
                        heartRate: heartRateStats,
                        bloodPressure: bloodPressureStats,
                        bloodOxygen: bloodOxygenStats,
                        bodyTemperature: bodyTemperatureStats
                    }, '统计所有健康数据成功');
                default:
                    return Result.error('Invalid type');
            }
        } catch (e) {
            console.error('Error in getStatistics:', e);
            return Result.error(e.message);
        }
    },
};

export default healthDataService;
